package top.kiterunner.learning.concurrency_test.ReentrantLockDemo;

// ReentrantLock可以设定为公平锁

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/10.
 */
public class ReentrantLockDemo4 {

    public Lock lock = new ReentrantLock(true);

    public void method1() {
        try {
            ;
            System.out.println(LocalDateTime.now() + " [" + Thread.currentThread().getName() + " Requesting Lock...]");
            lock.lock();
            System.out.println(LocalDateTime.now() + " [" + Thread.currentThread().getName() + " Get Lock...]");
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            System.out.println(LocalDateTime.now() + " [" + Thread.currentThread().getName() + " Requesting Lock...]");
            lock.lock();
            System.out.println(LocalDateTime.now() + " [" + Thread.currentThread().getName() + " Get Lock...]");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo4 rcd4 = new ReentrantLockDemo4();

        new Thread(rcd4::method1, "Thread_LONG").start();

        for (int i = 0; i < 3; i++) {
            new Thread(rcd4::method2, "Thread_" + i).start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
